#include "player.hpp"

const short unitsToEnergyTable[]   = {0, 0, 1, 1,  2,  3,  5,  7,  9, 12,  20};
const short unitsToVelocityTable[] = {0, 3, 6, 8, 12, 15, 20, 30, 40, 60, 120};

short unitsToVelocity(short units)
{
	if (units >= 0)
		return unitsToVelocityTable[units];
	else
		return -unitsToVelocityTable[-units];
}

short unitsToEnergy(short units)
{
	return unitsToEnergyTable[units];
}


short vectorModulo(short x, short y)
{
	return abs(x) + abs(y);
}

bool Player::adjustVelocity(short x, short y)
{
	velx += x;
	vely += y;
	return velocityModulo() <= getMaxVelocity();
}

bool Player::adjustDurability(short value)
{
	if ((durability += value) <= 0) {
		kill();
		return false;
	}
	else
		return true;
}

void Player::adjustEnergy(short value)
{
	energy += value;
	if (energy > maxEnergy)
		energy = maxEnergy;
}

void Player::brake()
{
	velx = 0;
	vely = 0;
}

bool Player::isCouldShoot(short tx, short ty)
{
	if (vectorModulo(x - tx, y - ty) > shootSector)
		return false;
	if (velocityModulo() == 0)
		return true;

	// (a^b) < pi/8
	// (a, b) == |a|*|b|*cos(a^b) > |a|*|b|*cos(pi/8)
	// both sides to the power of 2
	// (a, b)^2 > |a|^2*|b|^2*(cos(pi/8)^2)
	// and finally
	// (a, b)^2 > (a, a)*(b, b)*(cos(pi/8)^2)
	static const float cos_pi8_squared = 0.85355339059327376220042218105242f; // (cos(pi/8))^2

	float x1 = velx, y1 = vely;
	float x2 = tx - x, y2 = ty - y;
	float dotProduct = x1*x2 + y1*y2;

	return dotProduct*dotProduct > (x1*x1 + y1*y1)*(x2*x2 + y2*y2)*cos_pi8_squared;
}

